package org.domain.rescue2011.entity;

import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

@Name("autenticador")
public class Autenthicator {
	@In
	EntityManager entityManager;
	@In
	Credentials credentials;
	@In
	Identity identity;

	public boolean authenticate() {
		try {
			Usuario user = (Usuario) entityManager
					.createQuery(
							"from Usuario where username = :username and password = :password")
					.setParameter("username", credentials.getUsername())
					.setParameter("password", credentials.getPassword())
					.getSingleResult();
			if (user.getRol() != null) 
					identity.addRole(user.getRol().getNombreRol());
			
			return true;
		} catch (NoResultException ex) {
			return false;
		}
	}
}
